import requests


def request_build_components(request_body):
    url = 'http://ci.openharmony.cn/api/daily_build/build'
    headers = {"content-type": "application/json"}
    payload = {
        "branch": "master",
        "components": [],
        "deviceLevel": "",
        "endTime": '',
        "pageNum": 1,
        "pageSize": 50,
        "projectName": "openharmony",
        "startTime": '',
        "sortField": "",
        "sortType": "",
        "type": '1',
    }
    payload.update(request_body)
    response = requests.post(url, json=payload, headers=headers)

    if response.status_code != 200:
        raise
    return response.json()


def request_version_build(request_body):
    """
    :param request_body:
    :return:
    """
    url = 'http://ci.openharmony.cn/api/daily_build/build/list/component'
    headers = {"content-type": "application/json"}
    payload = {
        "projectName": "openharmony",
        "branch": "master",
        "pageNum": 1,
        "pageSize": 50,
        "deviceLevel": "",
        "component": '',
        "type": 0,
        "startTime": '',
        "endTime": '',
        "sortType": "",
        "sortField": "",
        "hardwareBoard": "",
        "buildStatus": "",
        "buildFailReason": ""
    }

    payload.update(request_body)
    response = requests.post(url, json=payload, headers=headers)

    if response.status_code != 200:
        raise
    return response.json()


def request_tag_build(request_body):
    """
    请求CI的tag系统接口
    :return:
    """
    # start_time = start_time[:10]
    # end_time = end_time[:10]
    url = 'http://ci.openharmony.cn/api/codecheckAccess/tag/build'
    headers = {"content-type": "application/json"}
    payload = {
        "projectName": "",
        "branch": "",
        "manifestFile": "",
        "searchName": "",
        "startTime": "",
        "endTime": "",
        "pageNum": 1,
        "pageSize": 50,
        "isDailyAnalysis": 0,
    }
    payload.update(request_body)
    response = requests.post(url, json=payload, headers=headers)

    if response.status_code != 200:
        raise
    return response.json()


def filter_tag(component, start_time, end_time, tag):
    if not (start_time < tag['timestamp'] < end_time) or not tag['prList']:
        return
    issue = tag['issue']
    if not issue:
        return
    last_comment = get_last_build_img(component, issue)
    if not last_comment:
        return
    trigger = last_comment['timestamp']
    build_time = '{}-{}-{} {}:{}:{}'.format(trigger[:4], trigger[4:6], trigger[6:8], trigger[8:10], trigger[10:12], trigger[12:])
    version_url = last_comment['versionUrl']
    pr = last_comment['pr']

    return {
        'merge_time': tag['timestamp'],
        'version_url': version_url,
        'pr': pr,
        'build_time': build_time,
    }


def get_last_build_img(build_target='dayu200', issue=''):
    """
    :param build_target: 形态
    :param issue:
    :return:
    """
    if not issue:
        return
    # gitee上的issue不带oh
    issue = issue.replace('http://gitee.com', 'http://openharmony.gitee.com')
    url = 'http://ci.openharmony.cn/api/codecheckAccess/ci-portal/v1/pipelines'

    params = {
        'buildTarget': build_target,
        'causeUrl': issue
    }
    try:
        rsp_data = requests.get(url, params=params).json()
        comment_list = rsp_data['data']
        comment_list.sort(key=lambda c: ['timestamp'], reverse=True)
        for comment in comment_list:
            if comment['versionUrl'] and comment['timestamp']:
                return comment
        return {}
    except Exception as e:
        return {}


def get_img_size(img_link):
    """
    获取文件大小
    :param img_link:
    :return:
    """
    if not img_link:
        return
    # 单位Byte
    return int(requests.head(img_link).headers['Content-Length'])


def download_img(img_link, start_size, end_size):
    headers = {
        'Range': 'bytes={}-{}'.format(start_size, end_size)
    }

    return requests.get(img_link, headers=headers, stream=True)


def ci_projects():
    """
    获取每日构建的项目和分支
    :return:
    """
    url = 'http://ci.openharmony.cn/api/dataService/data/ci-portal/v1/ci/projects'
    headers = {"content-type": "application/json"}
    response = requests.get(url, headers=headers)

    if response.status_code != 200:
        return {}
    json_data = response.json()

    return json_data['data']['projects']


def get_tag_projects():
    """
    获取tag系统的项目名称分支以及manifest.xml
    :return:
    """
    url = 'http://ci.openharmony.cn/api/codecheckAccess/tag/config'
    headers = {"content-type": "application/json"}
    response = requests.get(url, headers=headers)

    if response.status_code != 200:
        return {}
    json_data = response.json()

    return json_data['data']


def get_build_events(request_params):
    if not request_params:
        request_params = {}
    url = 'http://ci.openharmony.cn/api/codecheckAccess/ci-portal/v1/events'
    headers = {"content-type": "application/json"}
    params = {
        'pageNum': 1,
        'pageSize': 50,
        'projectName': '',
        'branch': '',
        'buildFailType': '',
        'startTime': '',
        'endTime': '',
        'triggerUser': '',
    }
    params.update(request_params)
    response = requests.get(url, params=params, headers=headers)
    return response.json()


def get_build_files(directory_url):
    url = 'http://ci.openharmony.cn/api/dataService/ci-portal/v1/files'
    headers = {"content-type": "application/json"}
    params = {'directoryUrl': directory_url}
    response = requests.get(url, params=params, headers=headers)
    return response.json()
